package com.ias.agdis_r.util.network;

import android.util.Base64;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.ias.agdis_r.R;
import com.ias.agdis_r.bean.user.UserInfoBean;
import com.ias.agdis_r.manager.ActionManager;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.module.ParameterModel;
import com.ias.agdis_r.module.RestfulUri;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.request.BaseRequest;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.request.BaseRequestHeader;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponse;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponseHeader;
import com.ias.agdis_r.terminalmanager.restful.security.endpoint.request.LoginRequest;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.sdcard.WriteLog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.security.MessageDigest;

public class HttpUtil {

	private static HttpUtil instance = null;// 单例的数据库管理器
	private RequestQueue requestQueue;

	public HttpUtil()
	{
		requestQueue = Volley.newRequestQueue(DataBaseManager.getInstance().getContext());
	}
	
	/**
	 * 单例模式
	 * 
	 * @return
	 */
	public static HttpUtil getInstance() {
		if (instance == null) {
			instance = new HttpUtil();
		}
		return instance;
	}

	/**
	 * 发送登录请求消息
	 * 
	 * @param userId
	 * @param pwd
	 * @param flag
	 */
	public void sendLoginRequeset(String userId, String pwd, String flag) {
		LoginRequest loginRequest = new LoginRequest();

		BaseRequestHeader header = loginRequest.getHeader();
		header.setUserId(userId);
		header.setPassword(pwd);
		header.setChannelId(ParameterModel.IMEI_ID);
		header.setServiceId(MessageModel.RELI);
		String tokenId = getTokenId(header);
		header.setToken(tokenId);

		loginRequest.setFlg(flag);
		sendRequestAction(loginRequest, true);

	}

	/**
	 * 发送请求消息,只需要处理Body部分（适用于登录后的网络请求）
	 * 
	 * @param requestBean
	 * @param serviceId
	 */
	public void sendRequest(BaseRequest requestBean, String serviceId,
			boolean showProgress) {
		BaseRequestHeader header = getHeader(serviceId);
		requestBean.setHeader(header);
		sendRequestAction(requestBean, showProgress);
	}

	/**
	 * 发送请求消息
	 * 
	 * @param requestBean
	 */
	private void sendRequestAction(BaseRequest requestBean, boolean showProgress) {
		try {

			String uri = RestfulUri.getUri(requestBean.getHeader()
					.getServiceId());
			// 如果未获取到uri
			if (S.isEmpty(uri)) {

				return;
			}
			// 大写变量会被转成小写
			// String json = mapper.writeValueAsString(requestBean);
			String json = null;
			try {
				json = DataManager.getInstance().getMapper().writeValueAsString(requestBean);
			} catch (IOException e) {
				e.printStackTrace();
				return;
			}
			WriteLog.getInstance().writeDebugLog("DEBUG---Request:"+json);
			Request<JSONObject> request = new JsonObjectRequest(uri,
					new JSONObject(json), new SuccesCallBack(requestBean
							.getHeader().getToken(), requestBean.getClass()
							.getName(), requestBean.getHeader().getServiceId(),
							showProgress), new ErrorCallBack(requestBean.getHeader().getServiceId(),showProgress));
			request.setRetryPolicy(new DefaultRetryPolicy(50000,
					DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
			requestQueue.add(request);
			// 如果显示进度条
			if (showProgress) {
				// 显示进度条
				ActionManager.getInstance().showProgress();
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取登录后的header
	 * 
	 * @param serviceId
	 * @return
	 */
	private BaseRequestHeader getHeader(String serviceId) {
		UserInfoBean userInfo = JavaBeanManager.getInstance().getUserinfo();
		String userId = userInfo.getEnb();
		BaseRequestHeader header = new BaseRequestHeader();
		header.setUserId(userId);
		header.setChannelId(ParameterModel.IMEI_ID);
		header.setServiceId(serviceId);
		String tokenId = getTokenId(header);
		header.setToken(tokenId);

		return header;
	}

	/**
	 * 请求成功回调
	 */
	class SuccesCallBack implements Response.Listener<JSONObject> {
		private String token = "";
		private String serviceId = "";
		private boolean showProgress = false;
		private String requestClasstName = "";

		public SuccesCallBack(String token, String requestClasstName,
				String serviceId, boolean showProgress) {
			super();
			this.token = token;
			this.serviceId = serviceId;
			this.showProgress = showProgress;
			this.requestClasstName = requestClasstName;
		}

		@Override
		public void onResponse(JSONObject jsonObj) {
			
			try {
				WriteLog.getInstance().writeDebugLog("DEBUG---Response:" + jsonObj);
				//反射Response名称，直接将Request替换为Response
				//若有错误，请检查对应类的名称
				String responseName = requestClasstName.replace("request", "response");
				responseName = responseName.replace("Request", "Response");
				Class<BaseResponse> responseClass = (Class<BaseResponse>) Class.forName(responseName);
				BaseResponse response = (BaseResponse) DataManager.getInstance().getMapper().readValue(jsonObj.toString(), responseClass);
				BaseResponseHeader header = response.getHeader();
				String rtoken = header.getToken();
				//如果token一致，处理消息
				if(rtoken.equals(token))
				{
					ActionManager.getInstance().handleResponse(this.serviceId, response);
				}
		
			}catch (Exception e) {
				e.printStackTrace();
			}
			finally
			{
				//如果显示了进度条，隐藏进度条
				if(showProgress)
				{
					ActionManager.getInstance().hideProgress();
				}
			}

		}

	}

	/**
	 * 请求失败回调
	 */
	class ErrorCallBack implements Response.ErrorListener {
		private boolean showProgress = false;
		private String serviceId = "";

		public ErrorCallBack(String serviceId, boolean showProgress) {
			this.showProgress = showProgress;
			this.serviceId = serviceId;
		}

		@Override
		public void onErrorResponse(VolleyError e) {

			String errorMsg = "";
			if (e instanceof TimeoutError) {
				//请求超时
				errorMsg = DataBaseManager.getInstance().getContext().getString(R.string.request_err_timeout);
			} else if (e instanceof ServerError) {
				//显示接收消息异常
				errorMsg = DataBaseManager.getInstance().getContext().getString(R.string.request_err_servererror);
			} else if (e instanceof NoConnectionError) {
				//无网络连接
				errorMsg = DataBaseManager.getInstance().getContext().getString(R.string.request_err_noconnection);
			}
			//如果显示进度条，才弹出错误信息的吐司
			if (showProgress) {
				ActionManager.getInstance().hideProgress();
				EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK,
						errorMsg, false);
			}
			e.printStackTrace();
			WriteLog.getInstance().writeDebugLog("DEBUG---请求结果:"+e.getMessage());
		}
	}

	/**
	 * 获取TokenId
	 * 
	 * @param header
	 * @return
	 */
	public String getTokenId(BaseRequestHeader header) {
		StringBuffer sb = new StringBuffer();
		sb.append(header.getUserId());
		sb.append(header.getChannelId());
		sb.append(header.getServiceId());

		MessageDigest msgDigest;
		try {
			msgDigest = MessageDigest.getInstance("SHA-1");
			byte[] hashedBytes = msgDigest.digest(sb.toString().getBytes(
					"UTF-8"));
			return Base64.encodeToString(hashedBytes, Base64.DEFAULT).replace(
					"\n", "");
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "";
	}
}
